package com.leetcode.根据数据结构分类.二叉树;

import com.leetcode.datastructure.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author: ZhouBert
 * @date: 2020/11/25
 * @description: 二叉树的层序遍历 https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
 */
public class B_102_二叉树的层序遍历 {


	/**
	 * 只能说，so easy
	 * @param root
	 * @return
	 */
	public List<List<Integer>> levelOrder(TreeNode root) {
		List<List<Integer>> res = new ArrayList<>();
		if (root == null) {
			return res;
		}
		//
		Queue<TreeNode> queue = new LinkedList<>();
		int size = 0;
		TreeNode cur = root;

		queue.offer(cur);
		size++;
		while (!queue.isEmpty()) {
			List<Integer> tempList = new ArrayList<>();
			int tempSize = size;
			size = 0;
			for (int i = 0; i < tempSize; i++) {
				cur = queue.poll();
				tempList.add(cur.val);
				if (cur.left != null) {
					queue.offer(cur.left);
					size++;
				}
				if (cur.right != null) {
					queue.offer(cur.right);
					size++;
				}
			}
			res.add(tempList);
		}
		return res;
	}


	/**
	 * 这是通过良好习惯 + 伪代码验证以后，开始写的代码！
	 *
	 * @param root
	 * @return
	 */
	public static void levelOrder4print(TreeNode root) {
		if (root == null) {
			return;
		}
		//添加一些辅助 ADT
		Queue<TreeNode> queue = new LinkedList<>();
		int size = 0;
		TreeNode cur = root;
		//对辅助 ADT 进行设置
		queue.offer(cur);
		size++;
		while (!queue.isEmpty()) {
			int tempSize = size;
			size = 0;
			for (int i = 0; i < tempSize; i++) {
				cur = queue.poll();
				System.out.print(cur.val + " ");
				if (cur.left != null) {
					queue.offer(cur.left);
					size++;
				}
				if (cur.right != null) {
					queue.offer(cur.right);
					size++;
				}
			}
			System.out.println();
		}
	}


	/**
	 * 层次遍历
	 * @return
	 */
	public static List<List<Integer>> leverOrderByIterator(TreeNode root){
		List<List<Integer>> res = new ArrayList<>();
		return null;
	}


	public static void main(String[] args) {
		TreeNode root = new TreeNode(3);
		root.left = new TreeNode(9);
		root.right = new TreeNode(20);
		root.right.left = new TreeNode(15);
		root.right.right = new TreeNode(7);

		levelOrder4print(root);
	}

	static void testLevelOrderByIterator(){

	}
}
